//index.js
//获取应用实例
const app = getApp();
var userInfo;
const DB = wx.cloud.database()
var that;
Page({
  data: {
    phone_numble: '',
    userType: '',
  },


  //用户授权登录登录
  loginGetUserInfo: function (e) {
    getApp().sendMsg()

    var that = this;
    let iv = e.detail.iv
    if (e.detail.iv == undefined) { //如果用户拒绝授权
    } else {
      wx.getUserInfo({ //调用授权api，获取用户信息
        success: function (res) {
          var userInfo = res.userInfo
          wx.cloud.callFunction({
            name: "openId",
            data: {},
            success(res) {
              var openid = res.result.openid;
              userInfo.openid = openid;

              DB.collection('user').get({
                  success: function (res) {
                    console.log('=============>', res.data)
                    var is_my =false;
                    res.data.forEach(item=>{
                      if(item._openid == openid){
                        is_my=item
                      }
                    })
                    if (is_my&&is_my.userInfoDetail.nicheng) {
                      wx.setStorageSync('userInfo', is_my)
                      wx.reLaunch({
                        url: '/pages/find/index?nav_type=login' // 这里是要跳转的路径
                      })
                    }else if (is_my&&!is_my.userInfoDetail.nicheng) {
                      wx.setStorageSync('userInfo', is_my)
                      wx.reLaunch({
                        url: '/pages/find/index?nav_type=login' // 这里是要跳转的路径
                      })
                    } else {
                      userInfo.userInfoDetail = {};
                      userInfo.id_num = 6230001+ res.data.length;
                      userInfo.seeNum=0
                      userInfo.tiwenNum=0
                      userInfo.zan_openid=[]
                      console.log('-------',userInfo.id_num,res.data.length)
                      DB.collection('user').add({
                        data: userInfo,
                        success: function (res) {
                          console.log('添加用户', res)
                          userInfo._id = res._id;
                          wx.setStorageSync('userInfo', userInfo)
                          wx.reLaunch({
                            url: '/pages/find/index?nav_type=login' // 这里是要跳转的路径
                          })
                        }
                      })
                    }
                  }
                })
            },
            fail(res) {
              console.log('333333333失败', res)
            }
          })
        }
      })
    }
  },

  onShow() {
    wx.cloud.callFunction({
      name: "openId",
      success(res) {
        let openId = res.result.openid
        console.log('我的openid', openId)
        // 判断数据库中是否已经有数据
        DB.collection('user').where({
          _openid: openId,
          })
          .get().then(ress => {
            console.log('ressressressressressressressress', ress.data[0])

            if (ress.data.length == 0) {
            } else {
              wx.setStorageSync('userInfo', ress.data[0]);
              if (!ress.data[0]||!ress.data[0].userInfoDetail.nicheng) {
                wx.reLaunch({
                  url: '/pages/find/index?nav_type=login'
                })
                return
              }
              console.log('!ress.data[0].character_list',!ress.data[0].character_list)
              if (!ress.data[0].character_list||ress.data[0].character_list.length==[]) {
                wx.navigateTo({
                  url: '/pages/character_list/index',
                })
                return
              }
              if (ress.data[0] && ress.data[0].userInfoDetail && ress.data[0].userInfoDetail.name) {
                wx.reLaunch({
                  url: '/pages/index/index'
                })
              }
            }
          })
      },
      fail(res) {
        console.log('登录失败', res)
      }
    })
    
  },

  getPhoneNumber: function (e) {
    var that = this;
    if (!e.detail.errMsg || e.detail.errMsg != "getPhoneNumber:ok") {
      wx.showModal({
        content: '请打开设置授权手机号',
        showCancel: false
      })
      return;
    }
    var data = {
      encryptedData: e.detail.encryptedData,
      iv: e.detail.iv,
      sessionCode: app.globalData.sessionCode // 这个通过wx.login获取，去了解一下就知道。这不多描述
    }
    console.log('data', data)
    wx.cloud.callFunction({
      name: 'getToken', // 对应云函数名
      data: data,
      success: res => {
        wx.hideLoading()
        console.log('data拿到手机号', data)
        console.log('成功拿到手机号，跳转首页', res.result)
        let phoneNumber = res.result.data.phoneNumber
        wx.setStorageSync('phoneNumber', phoneNumber)
        DB.collection('user').where({
            phoneNumber: 'phoneNumber',
          })
          .get({
            success: function (res) {
              console.log(res.data)
              if (res.data.length == 0) {
                console.log('数据未存在', res)
                DB.collection('user').add({
                  data: {
                    phoneNumber: phoneNumber,
                    zan_openid:[],
                    seeNum:0,
                    tiwenNum:0,
                  },
                  success: function (res) {
                    console.log(res)
                    console.log('储存数据', res)
                    wx.setStorageSync('phoneNumber_id', res._id)
                    wx.reLaunch({
                      url: '/pages/find/index?nav_type=login' // 这里是要跳转的路径
                    })
                  }
                })
              } else {
                console.log('数据已经存在', res)
                // wx.getStorageSync('phoneNumber_id'
                if (!res.data[0].userList) {
                  wx.getStorageSync('phoneNumber_id', res.data[0]._id)
                  wx.reLaunch({
                    url: '/pages/find/index?nav_type=login' // 这里是要跳转的路径
                  })
                } else if (!res.data[0].character_list) {
                  wx.setStorageSync('phoneNumber_id', res.data[0]._id);
                  wx.reLaunch({
                    url: '/pages/character_list/index' // 这里是要跳转的路径
                  })
                } else {
                  wx.setStorageSync('userARR', res.data[0]);
                  wx.reLaunch({
                    url: '/pages/character_list/index' // 这里是要跳转的路径
                  })
                }
                // wx.reLaunch({
                //   url: '/pages/index/index' // 这里是要跳转的路径
                // }) 
              }
            }
          })



      },
      fail: err => {
        console.error(err);
        wx.showToast({
          title: '获取手机号失败',
          icon: 'none'
        })
      }
    })
  },
  radioChange(e) {
    console.log('radio发生change事件，携带value值为：', e.detail.value)
    this.setData({
      userType: e.detail.value
    })
  },
  phone(e) {
    console.log('获取手机号', e.detail.value)
    this.setData({
      phone_numble: e.detail.value
    })
  },
  onLoad(op) {
    that = this;
    if (op.share_id) {
      wx.setStorageSync('share_id', share_id)
    }
    return
    if (wx.getStorageSync('phoneNumber')) {
      DB.collection('user').where({
          phoneNumber: wx.getStorageSync('phoneNumber'),
        })
        .get({
          success: function (res) {
            console.log(111111111111, res)
            if (res.data.length != 0) {
              if (!res.data[0].userList) {
                wx.setStorageSync('phoneNumber_id', res.data[0]._id);
                wx.reLaunch({
                  url: '/pages/find/index' // 这里是要跳转的路径
                })
              } else if (!res.data[0].character_list) {
                wx.setStorageSync('phoneNumber_id', res.data[0]._id);
                wx.reLaunch({
                  url: '/pages/character_list/index' // 这里是要跳转的路径
                })
              } else {
                wx.setStorageSync('userArr', res.data[0]);
                wx.switchTab({
                  url: '/pages/find/index',
                })
              }
            }
            // if()
          }
        })
    }

  },
  userAdd(openId) {
    var phone_numble = this.data.phone_numble;
    if (!phone_numble || phone_numble.length != 11) {
      wx.showToast({
        title: '手机号填写有误',
        icon: 'none'
      })
      return
    }
    if (this.data.userType == "我是老师") {
      console.log('是老师,填写的手机号码是', phone_numble)
      DB.collection('teacher').where({
          phone_numble: phone_numble,
        })
        .get().then(ress => {
          console.log('teacher-----ress.data', ress.data)
          // 判断老师的数据库里面有没有这个手机号 phone_numble
          if (ress.data.length > 0) {
            var user = {
              userType: this.data.userType,
              nickName: userInfo.nickName,
              avatarUrl: userInfo.avatarUrl,
              seeNum:0,
              tiwenNum:0,
              zan_openid:[],
              openId: openId
            };
            wx.setStorageSync('user', user);

            DB.collection('user').add({
              // data 字段表示需新增的 JSON 数据
              data: user
            }).then(res => {
              console.log(res)
              wx.setStorageSync("db_id", res._id)
              wx.switchTab({
                url: '/pages/studycentre/studycentre',
              })
            })
          } else {
            wx.showToast({
              title: '只有老师才可以登陆老师的身份哦',
              icon: 'none'
            })
            return
          }
        })
    } else {

      var user = {
        userType: this.data.userType,
        nickName: userInfo.nickName,
        avatarUrl: userInfo.avatarUrl,
        seeNum:0,
        tiwenNum:0,
        zan_openid:[],
        openId: openId
      };
      wx.setStorageSync('user', user);

      DB.collection('user').add({
        // data 字段表示需新增的 JSON 数据
        data: user
      }).then(res => {
        console.log(res)
        wx.setStorageSync("db_id", res._id)
        wx.switchTab({
          url: '/pages/studycentre/studycentre',
        })
      })
    }
  },
  getUserInfo: function (e) {
    if (!this.data.userType) {
      wx.showToast({
        title: '选择身份后才可登录',
        icon: 'none'
      })
      return
    }
    console.log(e)
    userInfo = e.detail.userInfo;

    wx.cloud.callFunction({
      name: "getOpenid",
      success(res) {
        let openId = res.result.userInfo.openId
        console.log('我的openid', openId)
        that.userAdd(openId)
        return
        // 判断数据库中是否已经有数据
        DB.collection('user').where({
            openId: openId,
          })
          .get().then(ress => {
            console.log('ressressressressressressressress', ress.data[0])

            if (ress.data.length == 0) {
              that.userAdd(openId)
            } else {
              wx.setStorageSync('user', ress.data[0]);
              wx.switchTab({
                url: '/pages/studycentre/studycentre',
              })
            }
          })
      },
      fail(res) {
        console.log('登录失败', res)
      }
    })

  }
})